package dshop.action.admin;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import appbase.jfinal.ext.ApiBaseController;
import appbase.jfinal.ext.ModelKit;
import appbase.jfinal.ext.RecordKit;
import appbase.utils.DateUtil;
import dshop.AppConst;
import dshop.interceptor.ApiAuthInterceptor;
import dshop.interceptor.ApiReadBodyParamInterceptor;
import dshop.model.Area;
import dshop.model.company.Company;
import dshop.model.company.CompanyAuthentication;
import dshop.model.company.CompanyAuthenticationImage;
import dshop.model.member.MemberCompany;
import dshop.model.member.MemberGeneralInfo;
import dshop.service.RedisService;

/**
 * 工厂管理
 */
@Before({ ApiReadBodyParamInterceptor.class, ApiAuthInterceptor.class })
public class CompanyAction extends ApiBaseController {

	public void authList() {
		String keyWord = getPara("keyWord", "").trim();
		String status = getPara("checkStatus", "").trim();
		// 排序
		String columnProp = getPara("columnProp", "").trim();
		String columnOrder = getPara("columnOrder", "").trim().split("ending")[0];

		String select = " select c.id, c.name, c.company_tel, c.intro, c.address,operator_time,operator, "
				+ " ca.account_id, ca.check_status, ca.check_status_explain, ca.check_date_time, ca.auth_img,"
				+ " concat(m.last_name, m.first_name) as real_name, m.phone, mc.company_id,add_time ";
		String where = " from company_authentication ca "
				+ " left join member_company mc on mc.account_id = ca.account_id "
				+ " left join company c on mc.company_id = c.id "
				+ " left join member_general_info m on m.account_id = ca.account_id " + " where 1 = 1 ";
		String orderBy = " order by ca.check_date_time desc ";

		List<Object> params = new ArrayList<Object>();
		if (!keyWord.isEmpty()) {
			where += " and ( c.name like ? or c.company_tel like ? or m.phone like ?)";
			String keyWordParam = "%" + keyWord + "%";
			params.add(keyWordParam);
			params.add(keyWordParam);
			params.add(keyWordParam);
		}
		if (!status.isEmpty()) {
			where += " and ca.check_status = ? ";
			params.add(status);
		}
		if (!columnOrder.isEmpty()) {
			orderBy = "order by " + columnProp + " " + columnOrder;
		}

		Page<Record> page = page(select, where + orderBy, params.toArray());
		List<Record> list = page.getList();

		RecordKit.putDateStr(list, "check_date_time", "check_date_time", "yyyy-MM-dd HH:mm");
		for (Record record : list) {
			Object object = record.get("auth_img");
			record.set("imageList", JSON.parseArray(ObjectUtils.defaultIfNull(object, "[]").toString(), String.class));
		}
//		CompanyAuthenticationImage.setImageListTo(list, "account_id", "imageList");

		renderSuccess();
	}

	public void authDetail() {
		int accountId = getParaToInt("accountId");
		CompanyAuthentication auth = CompanyAuthentication.dao.findById(accountId);
		auth.set("register_date", DateUtil.dateFormat(auth.getDate("register_date")));
		setAttr("auth", auth);
		auth.put("account", MemberGeneralInfo.dao.findById(accountId));
		auth.put("company", Company.getCompanyInfoByAccountId(accountId));

//		List<CompanyAuthenticationImage> authImageList = CompanyAuthenticationImage.dao.findByColumns("img", "account_id", accountId);
		setAttr("authImageList",
				JSON.parseArray(ObjectUtils.defaultIfNull(auth.getStr("auth_img"), "[]"), String.class));

		MemberGeneralInfo member = MemberGeneralInfo.dao.findById(accountId);
		setAttr("member", member);

		ModelKit.putDateFormat(auth, "check_date_time", "check_date_time_str", "yyyy-MM-dd HH:mm");

		renderSuccess();
	}

	public void checkStatusIng() {
		int accountId = getParaToInt("accountId");
		String remark = getPara("remark", "").trim();
		String checkStatus = AppConst.CHECK_STATUS_ING;

		CompanyAuthentication.setCheckStatus(accountId, checkStatus, remark);
		String userPhone = RedisService.getApiUserPhone(getParaToInt(ApiBaseController.PARAM_API_KEY_USER_ID));
		CompanyAuthentication.updateOperator(userPhone, accountId);

		renderSuccess("成功设置为审核中");
	}

	public void checkStatusPass() {
		int accountId = getParaToInt("accountId");
		String remark = getPara("remark", "").trim();
		String imageUrls = getPara("imageUrls", "").trim();

		String checkStatus = AppConst.CHECK_STATUS_PASS;

		String[] imageUrlArr = imageUrls.split("/-/");

		if (imageUrls.isEmpty() || imageUrlArr == null || imageUrlArr.length <= 0) {
			renderFail("请上传认证图片");
			return;
		}
		List<String> imageUrlList = new ArrayList<String>();
		for (String url : imageUrlArr) {
			if (StringUtils.isNotBlank(url)) {
				imageUrlList.add(url);
			}
		}
		CompanyAuthentication.dao.updateColumnBy("auth_img", "account_id", JSON.toJSONString(imageUrlList), accountId);

		String userPhone = RedisService.getApiUserPhone(getParaToInt(ApiBaseController.PARAM_API_KEY_USER_ID));
		CompanyAuthentication.updateOperator(userPhone, accountId);
//		CompanyAuthenticationImage.deleteBy(accountId);
//		CompanyAuthenticationImage.saveImageList(accountId, imageUrlArr);

		CompanyAuthentication.setCheckStatus(accountId, checkStatus, remark);

		renderSuccess("成功设置为已通过");
	}

	public void checkStatusFail() {
		int accountId = getParaToInt("accountId");
		String remark = getPara("remark", "").trim();
		String checkStatus = AppConst.CHECK_STATUS_FAIL;

		CompanyAuthentication.setCheckStatus(accountId, checkStatus, remark);

		String userPhone = RedisService.getApiUserPhone(getParaToInt(ApiBaseController.PARAM_API_KEY_USER_ID));
		CompanyAuthentication.updateOperator(userPhone, accountId);
		renderSuccess("已设置为不通过");
	}
}
